package com.maiji.cloud.controller;

import com.google.common.collect.Maps;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.UploadImageResData;
import com.maiji.cloud.utils.MaijiOSS;
import com.maiji.cloud.utils.UUID_MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@RestController
public class BaseController {

    protected static final String REST_URL_APPLOGIN = "http://MAIJICLOUD-APPLOGIN";
    @Autowired
    protected RestTemplate restTemplate;

    /**
     *  上传视频（批量）
     * @param uploadFiles
     * @param token
     * @return
     */
    @PostMapping("/uploadVideos")
    public BaseDataResDto<List<UploadImageResData>> uploadVideos (@RequestBody MultipartFile[] uploadFiles, @RequestHeader("maijiToken") String token) {
            Calendar calendar = Calendar.getInstance();
            String bucketName = "maiji-user-videos-" + calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH);
            return uploadRecord(uploadFiles, bucketName, token);
    }

    /**
     *  上传图片（批量）
     * @param uploadFiles
     * @param token
     * @return
     */
    @PostMapping("/uploadImage")
    public BaseDataResDto<List<UploadImageResData>> uploadImage (@RequestBody MultipartFile[] uploadFiles, @RequestHeader("maijiToken") String token) {
        Calendar calendar = Calendar.getInstance();
        String bucketName = "maiji-user-images-" + calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH);
        return uploadRecord(uploadFiles, bucketName, token);
    }

    public BaseDataResDto<List<UploadImageResData>> uploadRecord (MultipartFile[] uploadFiles, String bucketName, String token) {
        try {
            Map<String, Map<String, Object>> map = Maps.newHashMap();
            HttpHeaders headers = new HttpHeaders();
            headers.add("maijiToken", token);

            List<MultipartFile> uploadFilesArr = Arrays.asList(uploadFiles);
            uploadFilesArr.parallelStream().forEach( uploadFile -> {
                try {
                    String fileName = uploadFile.getOriginalFilename();
                    String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
                    String objName = UUID_MD5.getUUID() + "." + fileExtName;
                    if (MaijiOSS.aliyunOSSUpload(bucketName, objName, uploadFile.getInputStream())) {
                        Map<String, Object> mapObj = Maps.newHashMap();
                        mapObj.put("url", "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objName);
                        mapObj.put("bucketName", bucketName);
                        mapObj.put("no",uploadFilesArr.indexOf(uploadFile));
                        BufferedImage bufferedImage;
                        if (bucketName.contains("videos")) {
                            URLConnection connection = new URL("https://" + bucketName + ".oss-cn-beijing-internal.aliyuncs.com/"
                                    + objName + "?x-oss-process=video/snapshot,t_1000,f_jpg,ar_auto").openConnection();
                            bufferedImage = ImageIO.read(connection.getInputStream());
                            String imgUrl = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objName + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_500,ar_auto";
                            mapObj.put("imgUrl", imgUrl);
                        } else bufferedImage = ImageIO.read(uploadFile.getInputStream());
                        if (bufferedImage != null) {
                            mapObj.put("width", bufferedImage.getWidth());
                            mapObj.put("height", bufferedImage.getHeight());
                            map.put(objName, mapObj);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            HttpEntity<Map<String, Map<String, Object>>> httpEntity = new HttpEntity<>(map, headers);
            return restTemplate.postForObject(REST_URL_APPLOGIN + "/common/uploadRecord", httpEntity, BaseDataResDto.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseDataResDto(Status.ERROR);
        }
    }

    /**
     *  上传商品图片（批量）
     * @param uploadFiles
     * @return
     */
    @PostMapping("uploadGoodsImages")
    public BaseDataResDto<List<UploadImageResData>> uploadGoodsImages (@RequestBody MultipartFile[] uploadFiles) {
        String bucketName = "maiji-goods-images";
        return uploadRecord(uploadFiles, bucketName, null);
    }

    /**
     *  上传标签图片（批量）
     * @param uploadFiles
     * @return
     */
    @PostMapping("uploadLabelImages")
    public BaseDataResDto<List<UploadImageResData>> uploadLabelImages (@RequestBody MultipartFile[] uploadFiles) {
        String bucketName = "maiji-static-images";
        return uploadRecord(uploadFiles, bucketName, null);
    }

    /**
     *  上传食材图片（批量）
     * @param uploadFiles
     * @return
     */
    @PostMapping("uploadFoodImages")
    public BaseDataResDto<List<UploadImageResData>> uploadFoodImages (@RequestBody MultipartFile[] uploadFiles) {
        String bucketName = "maiji-food-images";
        return uploadRecord(uploadFiles, bucketName, null);
    }

    /**
     *  上传食谱图片（批量）
     * @param uploadFiles
     * @return
     */
    @PostMapping("uploadRecipeImages")
    public BaseDataResDto<List<UploadImageResData>> uploadRecipeImages (@RequestBody MultipartFile[] uploadFiles) {
        String bucketName = "maiji-recipe-images";
        return uploadRecord(uploadFiles, bucketName, null);
    }

    /**
     *  上传文章图片（批量）
     * @param uploadFiles
     * @return
     */
    @PostMapping("uploadArticleImages")
    public BaseDataResDto<List<UploadImageResData>> uploadArticleImages (@RequestBody MultipartFile[] uploadFiles) {
        String bucketName = "maiji-article-images";
        return uploadRecord(uploadFiles, bucketName, null);
    }

}
